package com.woniuxy.main.dynamic_lzq.hander;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.woniuxy.main.dynamic_lzq.dto.DynamicDto;
import com.woniuxy.main.dynamic_lzq.pojo.Dynamic;
import com.woniuxy.main.dynamic_lzq.pojo.DynamicComment;
import com.woniuxy.main.dynamic_lzq.pojo.User;
import com.woniuxy.main.dynamic_lzq.service.DynamicService;
import com.woniuxy.main.dynamic_lzq.service.UserService_Lzq;
import com.woniuxy.main.dynamic_lzq.test.MapDistance;
import com.woniuxy.main.login_yjj.pojo.User_Yjj;

import lombok.Data;

@Controller
@Data
public class DynamicHandler {
	
	@Autowired
	private   DynamicService dynamicService;
	@Autowired
	private  UserService_Lzq userService;
	//已知用户经纬度
	//主要展示广告，活动或用户，或场馆，或教练的信息
	//进入后显示全部信息以距离最近优先，发表时间其次优先。下滑更新。
	//遍历教练距用户、教练、场馆的距离，放入treemap
	@RequestMapping("/display")
	@ResponseBody
	public DynamicDto showDynamic(HttpServletRequest request){
		User_Yjj currentUser =  (User_Yjj)request.getSession().getAttribute("currentUser");
		sortDistance(currentUser.getLongitude(),currentUser.getLatitude());
		DynamicDto dto = showNearest();
		//System.out.println(dto.getUsers().toString());
		return dto;
	}

	
	static TreeMap<Double, User> distanceMap = new TreeMap<Double, User>();
	
	public   void sortDistance(double userLongitude,double userLatitude){
		List<User> users = userService.allUser();
		for(int i=0;i<users.size();i++){
			User user = users.get(i);
			double coachLongitude=user.getLongitude();
			double coachLatityde = user.getLatitude();
			//source的经纬度，target的经纬度
			double distance =  MapDistance.findDistance(userLongitude,userLatitude,coachLongitude,coachLatityde);
			user.setDistance(distance);
			distanceMap.put(distance, user);
		}
	}
	
	public  DynamicDto showNearest(){
		DynamicDto dto = new DynamicDto();
		List<User> usersList =new ArrayList<User>();
		List<Dynamic> dynamicsList = new ArrayList<Dynamic>();
		String key;         
        User user; 
		 Iterator it=distanceMap.entrySet().iterator(); 
		  while(it.hasNext()){  
              Map.Entry entry = (Map.Entry)it.next();         
              key=entry.getKey().toString();         
              user=(User) entry.getValue();         
             List<Dynamic> dynamics =  dynamicService.findDynamicByUid(user.getUser_id());
              	//System.out.println("教练:"+user.getUser_name()+"地址:"+user.getLatitude()+user.getDistance());
              	if(dynamics!=null){
              	for(int i=0;i<dynamics.size();i++){
              		Dynamic dynamic = dynamics.get(i);
       /*       		System.out.println("文字："+dynamic.getDynamic_detail());
              		System.out.println("时间"+dynamic.getDynamic_createtime());
              		System.out.println("图片"+dynamic.getImg1());*/
              		usersList.add(user);
              		
              		//每个图文找到评论
              		List<DynamicComment> comments = dynamicService.findCommentByDynamicId(dynamic.getDynamic_id());
              		dynamic.setComments(comments);
              		List<User> commentUsers = dynamicService.findUsersByDynamicId(dynamic.getDynamic_id());//该图文的评论人员信息
              		dynamic.setCommentUsers(commentUsers);
              		dynamicsList.add(dynamic);
              	}
              	//@select("select * from dynamic order by time desc limit 0,2")
            	  
            	  
            	/*  怎么找到最近的一条？怎么按顺序输出到前端？
            	 	迭代器遍历,输出user和dynamic信息*/
              	}
       }
		  dto.setUsers(usersList);
		  dto.setDynamics(dynamicsList);
		return dto; 
	}
	
	
	@RequestMapping("/addDynamic")
	@ResponseBody
	public void addDynamic(
			String dynamic_detail,
			@RequestParam("headImage") MultipartFile headImage,
			HttpServletRequest request
			){
		String name = headImage.getOriginalFilename();
		//获取webapps下的image文件夹
		String rootPath = request.getServletContext().getRealPath("");
		File rootFile = new File(rootPath);
		//File webappsFile =rootFile.getParentFile();
		File image = new File(rootFile, "dynamicImage");
		if (!image.exists()) {
			image.mkdirs();
		}
		//随机取名字
		String fileName = UUID.randomUUID().toString();
		fileName+=name.substring(name.indexOf("."));
		
		//将文件存放到image下
		File newFile = new File(image,fileName);
		try {
			headImage.transferTo(newFile);
			//将文件名存到数据库
			//.......
		} catch (Exception e) {
			e.printStackTrace();
		} ;
		dynamicService.addDynamic(dynamic_detail,"../chat/dynamicImage/"+fileName,request);
		System.out.println("提交成功！");
	}
	
	
	@RequestMapping("/addComment")
	@ResponseBody
	public void addComment(DynamicComment comment,HttpServletRequest request){
		User_Yjj currentUser =  (User_Yjj)request.getSession().getAttribute("currentUser");
		comment.setUser_id(currentUser.getUser_id());
		dynamicService.addComment(comment);
		
	}
	
	
	@RequestMapping("/retransmission")
	@ResponseBody
	public void retransmission(Dynamic dynamic,HttpServletRequest request){
		User_Yjj currentUser =  (User_Yjj)request.getSession().getAttribute("currentUser");
		//int user_id = (int) request.getSession().getAttribute("uid");
		int user_id=currentUser.getUser_id();
		dynamic.setUser_id(user_id);
		dynamicService.retransmission(dynamic);
	}
	
	@RequestMapping("/praise")
	@ResponseBody
	public void praise(int dynamic_id,HttpServletRequest request){
		User_Yjj currentUser =  (User_Yjj)request.getSession().getAttribute("currentUser");
		//int user_id = (int) request.getSession().getAttribute("uid");
		int user_id=currentUser.getUser_id();
		dynamicService.praise(user_id,dynamic_id);
	}
}
